package com.iman.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

public class BeanUtil {
    protected static final Log logger = LogFactory.getLog(BeanUtil.class);

    private BeanUtil() {
    }

    public static Field getDeclaredField(Object object, String propertyName) throws NoSuchFieldException {
        Assert.notNull(object);
        Assert.hasText(propertyName);

        return getDeclaredField(object.getClass(), propertyName);
    }

    public static Field getDeclaredField(Class clazz, String propertyName) throws NoSuchFieldException {
        Assert.notNull(clazz);
        Assert.hasText(propertyName);
        for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredField(propertyName);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + propertyName);
    }

    public static Object forceGetProperty(Object object, String propertyName) throws NoSuchFieldException {
        Assert.notNull(object);
        Assert.hasText(propertyName);
        Field field = getDeclaredField(object, propertyName);
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object result = null;
        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            logger.info("error wont' happen");
        }
        field.setAccessible(accessible);
        return result;
    }

    public static void forceSetProperty(Object object, String propertyName, Object newValue) throws NoSuchFieldException {
        Assert.notNull(object);
        Assert.hasText(propertyName);
        Field field = getDeclaredField(object, propertyName);
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        try {
            field.set(object, newValue);
        } catch (IllegalAccessException e) {
            logger.info("Error won't happen");
        }
        field.setAccessible(accessible);
    }

    public static Object invokePrivateMethod(Object object, String methodName, Object... params) throws NoSuchMethodException {
        Assert.notNull(object);
        Assert.hasText(methodName);
        Class[] types = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            types[i] = params[i].getClass();
        }
        Class clazz = object.getClass();
        Method method = null;
        for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                method = superClass.getDeclaredMethod(methodName, types);
                break;
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        if (method == null) {
            throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);
        }
        boolean accessible = method.isAccessible();
        method.setAccessible(true);
        Object result = null;
        try {
            result = method.invoke(object, params);
        } catch (Exception e) {
            ReflectionUtils.handleReflectionException(e);
        }
        method.setAccessible(accessible);
        return result;
    }

    public static List<Field> getFieldsByType(Object object, Class type) {
        List<Field> list = new ArrayList<Field>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType().isAssignableFrom(type)) {
                list.add(field);
            }
        }
        return list;
    }

    public static Class getPropertyType(Class type, String name) throws NoSuchFieldException {
        return getDeclaredField(type, name).getType();
    }

    public static String getGetterName(Class type, String fieldName) {
        Assert.notNull(type, "Type required");
        Assert.hasText(fieldName, "FieldName required");
        if (type.getName().equals("boolean")) {
            return "is" + StringUtils.capitalize(fieldName);
        } else {
            return "get" + StringUtils.capitalize(fieldName);
        }
    }

    public static Method getGetterMethod(Class type, String fieldName) {
        try {
            return type.getMethod(getGetterName(type, fieldName));
        } catch (NoSuchMethodException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    };

    // zhangwenzhi
    public static void copyNotNullProperties(Object dest, Object orig) {
        try {
            Map origmap = org.apache.commons.beanutils.BeanUtils.describe(orig);
            Set set = origmap.entrySet();
            Map tomap = new HashMap();
            for (Iterator iterator = set.iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object name = entry.getKey();
                Object v = entry.getValue();
                if (null != v)
                    tomap.put(name, v);
            }
            org.apache.commons.beanutils.BeanUtils.populate(dest, tomap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    };

    //zhangwenzhi 20090304
    public static void copyNotBlankProperties(Object dest, Object orig, String[] excludeProperties) {
        try {
            Map origmap = org.apache.commons.beanutils.BeanUtils.describe(orig);
            Set set = origmap.entrySet();
            Map tomap = new HashMap();
            for (Iterator iterator = set.iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object name = entry.getKey();
                Object v = entry.getValue();
                if (!"class".equals(name) && ArrayUtils.indexOf(excludeProperties, name.toString()) < 0)
                    if (v instanceof String) {
                        String va = (String) v;
                        if (StringUtils.isNotBlank(va))
                            tomap.put(name, v);
                    } else
                        tomap.put(name, v);
            }
            org.apache.commons.beanutils.BeanUtils.populate(dest, tomap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    //zhangwenzhi 20090304 
    public static final String getPropValueString(Object obj, String[] excludeProperties) {
        try {
            Map origmap = org.apache.commons.beanutils.BeanUtils.describe(obj);
            Set set = origmap.keySet();
            StringBuilder b = new StringBuilder();
            for (Iterator iterator = set.iterator(); iterator.hasNext();) {
                String key = (String) iterator.next();
                String value = (String) origmap.get(key);
                if (!"class".equals(key) && ArrayUtils.indexOf(excludeProperties, key) < 0)
                    b.append(value + " ");
            }
            return b.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    };

    public static void copyPropertiesByExclude(Object dest, Object orig, String[] excludeProperties) {
        try {
            Map origmap = PropertyUtils.describe(orig);
            Set set = origmap.entrySet();
            for (Iterator iterator = set.iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String name = entry.getKey().toString();
                Object v = entry.getValue();
                if (!"class".equals(name) && ArrayUtils.indexOf(excludeProperties, name.toString()) < 0)
                    org.apache.commons.beanutils.PropertyUtils.setProperty(dest, name, v);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    };
    
    public static void copyPropertiesByInclude(Object dest, Object orig, String[] includeProperties) {
        try {
            for (int i = 0; i < includeProperties.length; i++) {
                String property = includeProperties[i];
                org.apache.commons.beanutils.PropertyUtils.setProperty(dest, property, org.apache.commons.beanutils.PropertyUtils.getProperty(orig, property));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    };

}
